<?php

namespace Wanecho\Mobilelogin\Api\Listeners;

use Flarum\User\Event\Saving;
use Wanecho\Mobilelogin\Api\Validators\MobileValidator;
use Illuminate\Support\Arr;
use Flarum\Foundation\ValidationException;
use Wanecho\Mobilelogin\Api\WanechoSms;

class SavingValidate
{
    protected $validator;
    protected $valid_period = 30 * 3; // sms timeout 3 minute
    /**
     * @param HCaptchaValidator $validator
     */
    public function __construct(MobileValidator $validator)
    {
        $this->validator = $validator;
    }

    public function handle(Saving $event)
    {
        $mobile = Arr::get($event->data, 'attributes.mobile');
        $msgcode = (int) Arr::get($event->data, 'attributes.msgcode');
        if($event->actor->isAdmin()){
            $event->user->mobile = $mobile;
            return true;
        }
        if (!$event->user->exists) {
            $this->validator->assertValid([
                'mobile' => $mobile,
                'msgcode' => $msgcode
            ]);
            $sms_response = WanechoSms::where([
                'mobile' => $mobile,
            ])->orderBy('id', 'desc')->first();

            if (!$sms_response) {
                throw new ValidationException([
                    'msgcode' => '请先发送验证码',
                ]);
            }
            if ((int) $sms_response->code !== $msgcode) {
                throw new ValidationException([
                    'msgcode' => '短信验证码错误',
                ]);
            }
            $sms_response->is_active = 1;
            $sms_response->save();
            if ($sms_response->created_at > date('Y-m-d H:i:s', time() + $this->valid_period)) {
                throw new ValidationException([
                    'msgcode' => '短信验证码已过期，请重新获取',
                ]);
            }
            //
            $event->user->mobile = $mobile;

        }
    }
}